package com.fruits.login.service.impl;

import com.fruits.login.model.ReturnMsg;
import com.fruits.login.model.SmsCode;
import com.fruits.login.model.SmsCodeSingle;
import com.fruits.login.model.properties.LoginProperties;
import com.fruits.login.service.CodeService;
import com.fruits.util.SmsUtil;
import org.apache.commons.lang3.RandomStringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

@Service
public class CodeServiceImpl implements CodeService {

    private Logger logger = LoggerFactory.getLogger(getClass());

    private SmsCodeSingle smsCodeSingle = new SmsCodeSingle();

    @Override
    public String createAndSaveCode(String phone) {
        logger.info("createAndSaveCode:" + phone);
        String code = RandomStringUtils.randomNumeric(LoginProperties.SMS_CODE_SIZE);
        SmsCode smsCode = new SmsCode(code,phone);
        if (smsCodeSingle.addSmsCode(smsCode)){
            return code;
        }
        return null;
    }

    @Override
    public Boolean sendCode(String phone, String code) {
        String result = SmsUtil.sendSms(phone,
                "您的验证码是：" + code + " 验证码有效时间2分钟，请勿泄露给其他人。【宝石大乐斗】",null);
        logger.info("向手机:" + phone + "发送验证码" + code);
        if (Integer.parseInt(result) > 0) {
            return true;
        } else {
            System.out.println(SmsUtil.ErrorStr(result));
            //TODO 发送错误预警 可以不做
            return false;
        }
    }

    @Override
    public ReturnMsg checkCode(String phone, String code) {
        SmsCode smsCode = new SmsCode(code,phone);
        logger.info("检测验证码:" + smsCode.toString());
        return smsCodeSingle.checkSmsCode(smsCode);
    }

}
